package com.yami.shop.admin.controller;

import com.alibaba.fastjson.JSON;
import com.github.wxpay.sdk.WXPayUtil;
import com.google.zxing.qrcode.encoder.QRCode;
import com.yami.shop.admin.config.PayUtil;
import com.yami.shop.admin.config.QRCodeUtil;
import com.yami.shop.admin.config.WXPayService;
import io.micrometer.core.instrument.util.StringUtils;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wx/wxpay")
public class WxpayController {

    private String certPath = "resources/apiclient_cert.p12"; //注入证书路径

    private String notifyUrl = "https://www.xiaoerlangdang.com"; //回调地址(异步)


    /**
     * 映射微信支付
     *
     * @param amount  金额(单位：分)
     * @return
     */
    @RequestMapping("/getWxCode")
    public void wxPay(Integer amount,HttpServletResponse response) throws Exception {
        // 金额
        Double total_fee = 19.9;
        // 生成商家订单号
        String orderId = PayUtil.createOrder();
        if (total_fee > 0) {
            WXPayService wxPayService = WXPayService.getInstance(certPath, notifyUrl);
            String codeUrl = wxPayService.doUnifiedOrder(orderId, "小二啷当收银系统", total_fee, "001");
            // 生成支付二维码(数据流) 返回给前端页面
             QRCodeUtil.createQrCodeStream(codeUrl,900,"png",response);

            //QRCodeUtil.createQrCode("E:\\qrcode.jpg",codeUrl,900,"JPEG");
        }

    }





    /**
     *  支付成功,回调成功,返回xml类型的数据
     * @param returnCode
     * @param msg
     * @return
     * @throws Exception
     */
    private String setXml(String returnCode, String msg) throws Exception {
        Map<String,String> xmlMap = new HashMap<>();
        xmlMap.put("return_code",returnCode);
        xmlMap.put("return_msg",msg);
        String data = WXPayUtil.mapToXml(xmlMap);
        return data;
    }





}
